//
//  SimpleProfileView.swift
//  letusmeet_ios
//
//  Created by Rovo Dev on 2025/1/27.
//

import SwiftUI
import SwiftData

struct ProfileView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var userProfiles: [UserProfile]
    @Query private var activities: [Activity]
    
    @State private var isLoading = true
    @State private var selectedTab = 3
    
    private var currentUser: UserProfile {
        if let user = userProfiles.first {
            return user
        } else {
            let defaultUser = UserProfile(
                username: "张小明",
                userID: "20240101",
                level: "🌟 社交达人",
                createdActivities: 12,
                joinedActivities: 28,
                friendsCount: 15,
                tags: ["运动爱好者", "读书分享者", "户外探险家"],
                nickname: "张小明",
                gender: "男",
                age: 28,
                city: "北京",
                profession: "软件工程师"
            )
            modelContext.insert(defaultUser)
            return defaultUser
        }
    }
    
    private var userActivities: [Activity] {
        if activities.isEmpty {
            let sampleActivities = [
                Activity(title: "周末户外徒步", location: "城市公园", coverImage: "hiking"),
                Activity(title: "经典小说分享", location: "咖啡书店", coverImage: "reading"),
                Activity(title: "周末摄影交流", location: "城市广场", coverImage: "photography"),
                Activity(title: "城市美食探店", location: "美食街", coverImage: "food")
            ]
            sampleActivities.forEach { modelContext.insert($0) }
            return sampleActivities
        }
        return Array(activities.prefix(4))
    }
    
    var body: some View {
        ZStack {
            Color(NSColor.controlBackgroundColor)
                .ignoresSafeArea()
            
            if isLoading {
                LoadingView()
            } else {
                ScrollView {
                    VStack(spacing: 0) {
                        UserHeaderView(user: currentUser)
                        
                        VStack(spacing: 20) {
                            FunctionMenuView()
                            MyActivitiesView(activities: userActivities)
                            PersonalInfoView(user: currentUser)
                        }
                        .padding(.horizontal, 16)
                        .padding(.top, 20)
                        .padding(.bottom, 100)
                    }
                }
            }
            
            VStack {
                Spacer()
                BottomNavigationView(selectedTab: $selectedTab)
            }
        }
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                withAnimation(.easeInOut(duration: 0.5)) {
                    isLoading = false
                }
            }
        }
    }
}

struct LoadingView: View {
    @State private var isRotating = false
    
    var body: some View {
        VStack(spacing: 20) {
            Circle()
                .stroke(
                    LinearGradient(
                        colors: [.orange, .yellow],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: 4
                )
                .frame(width: 50, height: 50)
                .rotationEffect(.degrees(isRotating ? 360 : 0))
                .animation(
                    .linear(duration: 1)
                    .repeatForever(autoreverses: false),
                    value: isRotating
                )
            
            Text("加载中...")
                .font(.system(size: 16, weight: .medium))
                .foregroundColor(.secondary)
        }
        .onAppear {
            isRotating = true
        }
    }
}

struct UserHeaderView: View {
    let user: UserProfile
    
    var body: some View {
        VStack(spacing: 16) {
            ZStack {
                Circle()
                    .fill(Color.white.opacity(0.2))
                    .frame(width: 100, height: 100)
                    .overlay(
                        Circle()
                            .stroke(Color.white.opacity(0.3), lineWidth: 3)
                    )
                
                Text(user.avatar)
                    .font(.system(size: 40))
            }
            
            VStack(spacing: 8) {
                HStack(spacing: 8) {
                    Text(user.username)
                        .font(.system(size: 24, weight: .bold))
                        .foregroundColor(.white)
                    
                    Text(user.level)
                        .font(.system(size: 14, weight: .medium))
                        .foregroundColor(.white.opacity(0.9))
                }
                
                Text("ID: \(user.userID)")
                    .font(.system(size: 14))
                    .foregroundColor(.white.opacity(0.9))
            }
            
            HStack(spacing: 20) {
                StatItemView(number: user.createdActivities, label: "发起活动")
                StatItemView(number: user.joinedActivities, label: "参与活动")
                StatItemView(number: user.friendsCount, label: "好友数量")
            }
            
            TagsView(tags: user.tags)
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 40)
        .background(
            LinearGradient(
                colors: [Color.orange, Color.yellow],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
    }
}

struct StatItemView: View {
    let number: Int
    let label: String
    
    var body: some View {
        VStack(spacing: 4) {
            Text("\(number)")
                .font(.system(size: 20, weight: .bold))
                .foregroundColor(.white)
            
            Text(label)
                .font(.system(size: 12))
                .foregroundColor(.white.opacity(0.9))
        }
    }
}

struct TagsView: View {
    let tags: [String]
    
    var body: some View {
        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 2), spacing: 8) {
            ForEach(tags, id: \.self) { tag in
                Text(tag)
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.white)
                    .padding(.horizontal, 12)
                    .padding(.vertical, 6)
                    .background(Color.white.opacity(0.2))
                    .clipShape(Capsule())
            }
        }
        .padding(.top, 8)
    }
}

#Preview {
    ProfileView()
        .modelContainer(for: [UserProfile.self, Activity.self], inMemory: true)
}